<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--流程分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="categoryName"
              placeholder="请输入分类名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="categoryOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="categoryTreeRef"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form @submit.native.prevent :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="关键字" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输模板名称/模板Key"
                clearable
                style="width: 300px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['flowable:bpmn:modelInfo:add']"
            >新增
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">
                      <el-button
                        type="primary"
                        plain
                        icon="el-icon-caret-right"
                        @click="handleDeploy"
                        v-hasPermi="['system:notice:add']"
                      >发布</el-button>
                    </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="modelList" highlight-current-row
        >
          <el-table-column label="序号" align="center" type="index" width="100"/>
          <el-table-column
              label="名称"
              align="left"
              prop="name"
              width="300"
              :show-overflow-tooltip="true"
          />
          <el-table-column show-overflow-tooltip label="Key" align="left" prop="modelKey" width="150" :show-overflow-tooltip="true"/>
          <el-table-column show-overflow-tooltip label="分类名称" align="left" prop="categoryName" width="100"/>
          <el-table-column label="状态" align="center" prop="status" width="100">
            <template #default="scope">
              <el-tag effect="dark" type="success" v-if="scope.row.status === 'publish'">{{ scope.row.statusName }}
              </el-tag>
              <el-tag effect="dark" type="info" v-else-if="scope.row.status === 'draft'">{{ scope.row.statusName }}
              </el-tag>
              <el-tag effect="dark" type="info" v-else>{{ scope.row.statusName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="更新时间" align="center" prop="lastUpdated" width="150">
            <template #default="scope">
              <span>{{ parseTime(scope.row.lastUpdated, '{y}-{m}-{d} {hh}:{mm}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                  v-if="scope.row.status !== 'publish'"
                  link
                  type="primary"
                  icon="Position"
                  @click="handleDeploy(scope.row)"
              >发布
              </el-button>
              <el-button
                  link
                  type="primary"
                  icon="Edit"
                  v-hasPermi="['flowable:bpmn:modelInfo:edit']"
                  @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                  link
                  type="primary"
                  icon="Picture"
                  @click="handleBpmnPreview(scope.row)"
              >预览
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改流程对话框 -->
    <el-dialog fullscreen
               v-model="bpmnDialogVisible"
               append-to-body
               :close-on-press-escape="false"
               :show-close="false"
               :close-on-click-modal="false"
               class="bpmn-designer-body">
      <template #header="{ close, titleId, titleClass }">
        <div class="bpmn-designer-header">
          <div class="text-left bpmn-title">
            {{ title }}
          </div>
          <div class="bpmn-designer-step">
            <el-steps :active="active" finish-status="success" simple>
              <el-step >
                <template #title>
                  <!-- @click="handleStepClick(0)" -->
                  <div >基本信息</div>
                </template>
              </el-step>
              <el-step >
                <template #title>
                  <div >流程设计</div>
                </template>
              </el-step>
            </el-steps>
          </div>
          <div class="text-right bpmn-actions">
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <el-button :disabled="active < 1" type="primary" @click="handlePrev">上一步</el-button>
            <el-button :disabled="active > 0" type="primary" @click="handleNext">下一步</el-button>
            <el-button @click="cancel">关 闭</el-button>
          </div>
        </div>
      </template>
      <div class="bpmn-designer-container">
        <div v-show="active === 0" class="bpmn-base-info">
          <BpmnBaseInfo :category-code="currentRowData.categoryCode" :model-id="currentRowData.modelId" ref="bpmnBaseInfoRef"/>
        </div>
        <div v-if="active === 1" style="height: 100%;">
          <bpmn-designer :model-id="currentRowData.modelId" :model-key="currentRowData.modelKey" ref="bpmnDesignerRef"/>
        </div>
      </div>
    </el-dialog>

    <!-- 预览流程对话框 -->
    <el-dialog width="1000px"
               :title="bpmnViewerTitle"
               v-model="bpmnViewerVisible"
               append-to-body
               class="bpmn-viewer-body">
      <div style="height: 500px;">
        <BpmnViewer :model-key="previewModelKey" ref="bpmnViewerRef" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="BpmnModelList">
import {deployBpmnModel, getCategories, modelPage, saveBpmnModel} from "@/api/flowable/bpmn/modelInfo";
import BpmnDesigner from "@/views/flowable/bpmn/modelInfo/components/BpmnDesigner.vue";
import {listToTree} from "@/utils/treeHelper";
import BpmnBaseInfo from "./components/BpmnBaseInfo.vue";
import BpmnViewer from "../../components/BpmnViewer.vue";

const {proxy} = getCurrentInstance();
const active = ref(0);
// 遮罩层
const loading = ref(true);
const defaultProps = ref({
  children: "children",
  label: "name"
});
// 分类名称
const categoryName = ref(undefined);
const currentCategory = ref(undefined);
const currentRowData = ref(undefined);
const bpmnBaseInfoRef = ref();
const bpmnDesignerRef = ref();
// 显示搜索条件
const showSearch = ref(true);
const categoryOptions = ref(undefined);
// 总条数
const total = ref(0);
// 流程表格数据
const modelList = ref([]);
// 弹出层标题
const title = ref("");

// 是否显示弹出层
const bpmnDialogVisible = ref(false);

const previewModelKey = ref('');
const bpmnViewerTitle = ref('');
const bpmnViewerVisible = ref(false);

const bpmnViewerRef = ref(undefined);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    keyword: '',
  }
});

const { queryParams } = toRefs(data);

/** 根据名称筛选分类树 */
watch(categoryName, val => {
  proxy.$refs["categoryTreeRef"].filter(val);
});

/** 预览按钮操作 */
const handleBpmnPreview = (row) => {
  bpmnViewerTitle.value = "流程预览-" + row.name;
  bpmnViewerVisible.value = true;
  previewModelKey.value = row.modelKey;
  // currentRowData.value.modelKey = row.modelKey;
  // nextTick(() => {
  //   bpmnViewerRef.value.reloadViewerXML(row.modelKey, '');
  // })
}

const handlePrev =() =>{
  active.value -= 1;
}
const handleNext = async () =>{
  try {
    const baseInfo = await proxy.$refs.bpmnBaseInfoRef.submitForm(false);
    active.value += 1;
    currentRowData.value.modelKey = baseInfo.modelKey;
  } catch (e) {
  }
}

/** 查询流程列表 */
function getList() {
  loading.value = true;
  modelPage(queryParams.value).then(response => {
    modelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function handleStepClick(idx) {
  active.value = idx;
}

const submitForm = async () => {
  if(active.value === 1){
    const formData = await proxy.$refs.bpmnBaseInfoRef.getFormData();
    const {xml} = await proxy.$refs.bpmnDesignerRef.getBpmnXml();
    // 保存流程设计器xml
    const data = {
      modelId: formData.id,
      modelKey: formData.modelKey,
      modelName: formData.modelName,
      modelXml: xml,
      categoryCode: formData.categoryCode,
    };
    saveBpmnModel(data).then(res => {
      proxy.$modal.msgSuccess(res.msg);
    })

  }else if(active.value === 0){
    // 保存表单基本信息
    await proxy.$refs.bpmnBaseInfoRef.submitForm();
  }
}

// 节点单击事件
function handleNodeClick(data) {
  currentCategory.value = data;
  queryParams.value.category = data.code;
  handleQuery();
}

// 筛选节点
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
}

/** 查询部门下拉树结构 */
function getCategoryTree() {
  getCategories().then(response => {
    const treeList = response.data;
    categoryOptions.value = listToTree(treeList);
  });
}

// 取消按钮
function cancel() {
  bpmnDialogVisible.value = false;
  proxy.$refs.bpmnBaseInfoRef.reset();
  getList();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 选中数据 current
function handleCurrentChange(currentRow, oldCurrentRow) {
  currentRowData.value = currentRow;
}

/** 新增按钮操作 */
function handleAdd() {
  currentRowData.value = {
    categoryCode : !!currentCategory.value?currentCategory.value.code:''
  };
  bpmnDialogVisible.value = true;
  title.value = "添加流程";
  active.value = 0;
  proxy.$refs.bpmnBaseInfoRef.initData({categoryCode: currentRowData.value.categoryCoe})
}

/** 发布按钮操作 */
function handleDeploy(row) {
  proxy.$modal.confirm('是否确认发布名称为"' + row.name + '"的流程？').then(function() {
    return deployBpmnModel({id: row.id})
  }).then((res) => {
    proxy.$modal.msgSuccess(res.msg);
    // 刷新页面
    getList();
  }).catch((e) => {

  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  active.value = 0;
  currentRowData.value = row;
  currentRowData.value.categoryCode = row.category;
  bpmnDialogVisible.value = true;
  title.value = "编辑流程";
  proxy.$nextTick(() => {
    proxy.$refs.bpmnBaseInfoRef.initData({
      categoryCode: row.category,
      modelName: row.name,
      modelKey: row.modelKey
    })
  });

}

getList();
getCategoryTree();

</script>
<style lang="scss">
.bpmn-designer-body {
  display: flex;
  flex-direction: column;

  .bpmn-designer-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .bpmn-title {
      font-weight: bold;
      flex: 1;
    }

    .bpmn-actions {
      flex: 1;
    }

    .bpmn-designer-step {
      width: 300px;

      .el-steps--simple {
        background: transparent;
      }
    }
  }

  .el-dialog__body {
    padding: 0;
    flex: 1;

    .bpmn-designer-container {
      height: 100%;

      .bpmn-base-info {
        width: 500px;
        margin: auto;
      }
    }

  }
}
</style>
